using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Plugin.Api.Models.Plugin;
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Urs.Core;
using Urs.Core.Caching;
using Urs.Data.Domain.Configuration;
using Urs.Framework.Controllers;
using Urs.Services.Authentication.External;
using Urs.Services.Media;
using Urs.Services.Payments;

namespace Plugin.Api.Controllers
{
    /// <summary>
    /// 插件接口
    /// </summary>
    [ApiAuthorize]
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/plugin")]
    [ApiController]
    public class PluginController : BaseApiController
    {
        private readonly IOpenAuthenticationService _openAuthenticationService;
        private readonly StoreInformationSettings _storeInformationSettings;

        public PluginController(IOpenAuthenticationService openAuthenticationService,
            StoreInformationSettings storeInformationSettings)
        {
            this._openAuthenticationService = openAuthenticationService;
            this._storeInformationSettings = storeInformationSettings;
        }

        /// <summary>
        /// 微信支付[小程序]
        /// 【多人反馈问题】微信支付请设置StoreUrl，改地址为可访问地址，如果调制阶段应该为http://localhost:[端口] 否则会调用不到微信支付
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <param name="paytype">订单类型</param>
        /// <returns></returns>
        [HttpGet("weixinopenpaymenturl")]
        [ApiAuthorize]
        public async Task<ApiResponse<MoPayment>> WeixinOpenPayment(int orderId, string paytype)
        {
            var user = RegisterUser;
            var auth = _openAuthenticationService.GetExternalIdentifiersFor(user).FirstOrDefault(ear => ear.ProviderSystemName == "ExternalAuth.WeixinOpen");
            if (auth == null)
                return ApiResponse<MoPayment>.Warn("OpenId不能为空");

            var openId = auth.OpenId;
            var url = string.Format("{0}plugins/paymentweixinopen/payingapi?orderId={1}&paytype={2}&openId={3}", _storeInformationSettings.StoreUrl, orderId, paytype, openId);

            string http;
            try
            {
                http = await HttpHelper.HttpGetAsync(url);
                JObject o = JObject.Parse(http);
                if (o["Code"] != null && o["Code"].ToString() == "200")
                {
                    var data = Newtonsoft.Json.JsonConvert.DeserializeObject<MoPayment>(o["data"].ToString());

                    return ApiResponse<MoPayment>.Success(data);
                }
                return ApiResponse<MoPayment>.Warn(o["Content"].ToString());
            }
            catch (Exception ex)
            {
                return ApiResponse<MoPayment>.Warn(ex.Message);
            }
        }



    }
}
